package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.property.PropertyPadBotDeliveryTaskDTO;
import com.itlong.cloud.POJO.PO.PadBotRobotDeliveryTaskRecordPO;
import com.itlong.cloud.POJO.VO.app.RobotDeliveryTaskInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyDeliveryTaskGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.property.dao.IPropertyDeliveryTaskDao;
import com.itlong.cloud.property.service.IPropertyDeliveryTaskService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      机器人派送任务业务处理层接口
 * </desc>
 *
 * @createDate 2021/1/7
 **/
@Service
public class PropertyDeliveryTaskServiceImpl implements IPropertyDeliveryTaskService {


    @Autowired
    private IPropertyDeliveryTaskDao iPropertyDeliveryTaskDao;

    @Autowired
    private RedisService redisService;

    public static final String ROBOT_ID = "PW1090";

    public static final String MAP_ID = "2c928aa676f5b7dd0176f6720a421955";

    /**
     * <desc>
     *      获取配送任务分页列表
     * </desc>
     *
     * @param deliveryTaskDTO 配送任务参数DTO
     * @return 配送任务分页列表
     * @Author Zhu.yj
     * @createDate  2021/1/12
     */
    @Override
    public Page<PropertyDeliveryTaskGetPageVO> getPage(PropertyPadBotDeliveryTaskDTO deliveryTaskDTO) throws Exception {
        if (StringUtils.isBlank(deliveryTaskDTO.getOrderColumn()) || StringUtils.isBlank(deliveryTaskDTO.getOrderRule())){
            deliveryTaskDTO.setOrderColumn("createTime");
            deliveryTaskDTO.setOrderRule("DESC");
        }

        Page<PropertyDeliveryTaskGetPageVO> page = new Page<>();
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(deliveryTaskDTO);
        if (StringUtils.isNotBlank(deliveryTaskDTO.getDeliveryStatus())){
            params.put("deliveryStatusList", StringHandlerUtil.splitStringList(deliveryTaskDTO.getDeliveryStatus()));
        }
        page.getPage().setPageSize(deliveryTaskDTO.getPageSize());
        page.getPage().setCurrentPage(deliveryTaskDTO.getCurrentPage());
        params.put("pageSize", page.getPage().getPageSize());
        params.put("startSlip", page.getPage().getStartSlip());
        page.setRows(iPropertyDeliveryTaskDao.getPage(params), iPropertyDeliveryTaskDao.getPageCount(params));
        return page;
    }

    /**
     * <desc>
     *      获取目标点列表
     * </desc>
     *
     * @return 目标点信息
     * @Author Zhu.yj
     * @createDate  2021/1/8
     */
    @Override
    public List<Map<String, Object>> getTargetPointList(String phoneNum) throws Exception {
        //机器人id，目前只有这一个机器人id，所以直接写在代码中，后续再表中维护
        String serialNumber = ROBOT_ID;
        //地图id目前也只取一层，后续根据机器人id找到对应的地图,派送任务demo
        String mapId = MAP_ID;
        String redisMapId = redisService.get(RedisConstant.PADBOT_MAP_ID_CACHE_KEY);
        if (StringUtils.isNotBlank(redisMapId)){
            mapId = redisMapId;
        }
        List<Map<String, Object>> targetPointList = iPropertyDeliveryTaskDao.getTargetPointList(mapId);


        if (phoneNum != null && redisService.get(RedisConstant.PADBOT_TARGET_POT_PHONE_CACHE_KEY + phoneNum) != null){
            String userTargetPointId = redisService.get(RedisConstant.PADBOT_TARGET_POT_PHONE_CACHE_KEY + phoneNum);
            int i = 0;
            for (Map<String, Object> targetPointMap : targetPointList){
                String targetPointId = targetPointMap.get("targetPointId") == null ? null : targetPointMap.get("targetPointId").toString();
                if (targetPointId != null && targetPointId.equals(userTargetPointId)){
                    break;
                }
                i++;
            }
            //将用户的地址放在第一位
            if (i< targetPointList.size()){
                Collections.swap(targetPointList, i, 0);
            }
        }

        return targetPointList;
    }



    /**
     * <desc>
     *      修改配送任务状态
     * </desc>
     *
     * @param taskId 回调信息
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/12
     */
    @Override
    public boolean updateTaskStatus(String taskId, String status) throws Exception {
        if (StringUtils.isBlank(taskId) || StringUtils.isBlank(status)){
            return false;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("taskId", taskId);
        params.put("status", status);
        params.put("updateTime", new Date());
        return iPropertyDeliveryTaskDao.updateTaskStatus(params) > 0;
    }

    /**
     * <desc>
     *      回调接收派送任务信息
     * </desc>
     *
     * @param taskJson 派送任务信息
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/13
     */
    @Override
    public boolean receiveDeliveryTaskInfo(String taskJson) throws Exception {
        Date nowTime = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        RobotDeliveryTaskInfoVO taskInfoVO = JSON.parseObject(taskJson, RobotDeliveryTaskInfoVO.class);
        PadBotRobotDeliveryTaskRecordPO taskRecordPO =new PadBotRobotDeliveryTaskRecordPO();
        taskRecordPO.setTaskId(taskInfoVO.getTaskId());
        taskRecordPO.setPhoneNumber(taskInfoVO.getPhoneNumber());
        taskRecordPO.setPickPassword(taskInfoVO.getPickPassword());
        taskRecordPO.setOrderNumber(LogicIdUtil.bussinessId());
        taskRecordPO.setTargetPointId(taskInfoVO.getTargetPointId());
        taskRecordPO.setDeliveryStatus(Integer.valueOf(taskInfoVO.getDeliveryStatus()));
        taskRecordPO.setRobotNumber(taskInfoVO.getSerialNumber());
        taskRecordPO.setStatus(DataStatusEnum.NORMAL.getType());
        taskRecordPO.setCreateTime(dateFormat.parse(Long.toString(taskInfoVO.getCreateTime())));
        taskRecordPO.setUpdateTime(dateFormat.parse(Long.toString(taskInfoVO.getCreateTime())));
        return iPropertyDeliveryTaskDao.save(SqlUtil.durableData(taskRecordPO, PlatformConstants.TABLE_SAVE)) > 0;
    }

    /**
     * <desc>
     *      根据电话号码获取目标点
     * </desc>
     *
     * @param phoneNumber 电话号码
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/22
     */
    @Override
    public String getTargetPointId(String phoneNumber) throws Exception {
        return null;
    }

}
